#####################################
# SCRIPT TO GENERATE FIGURE 3       #
# PAPER: THE MILITARIZATION OF      #
# LAW ENFORCEMENT: EVIDENCE FROM    #
# LATIN AMERICA                     #
#####################################

#Download shapefiles
  #download.file(url = "http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip",destfile = "worldshape.zip")
  #unzip("worldshape.zip")

#Libraries
  require(rgdal)
  require(rgeos)
  require(maptools)
  require(dplyr)
  require(ggplot2)
  require(RColorBrewer)
  source('Fig3 Map Theme.R')
  require(scales)
  setwd("WORKING DIRECTORY")
  


# Shapefiles

  WorldShape <- readOGR(dsn = "Shape",layer = "TM_WORLD_BORDERS-0.3")
  WorldShape <- WorldShape[WorldShape$REGION==19 ,]
  WorldShape <- WorldShape[WorldShape$SUBREGION==5 | WorldShape$SUBREGION==13 | WorldShape$UN==214 | WorldShape$UN==332 ,]

#Data

  Map <- read.csv("Map Latin America.csv",stringsAsFactors = F)
  Map$id <- Map$fips
  Map <- left_join(Map,
                      data.frame(typology=0:3,
                                 typologytext=c('Militarized Police','Paramilitary Police','Limited constabularization of the military', 'Generalized constabularization of the military')))

#Fortify shape for ggplot2
  
  WorldShape@data$id <- WorldShape@data$FIPS
  WorldShape <- fortify(WorldShape, region='id')
  WorldShape <- left_join(WorldShape,Map)


#Draw map
  
  latam <- ggplot(data=WorldShape) +
           geom_polygon(aes(x=long,y=lat,group=group, fill=as.character(typologytext)),color='grey') +
           scale_fill_manual(values = c('#000000', '#525252' ,'#d9d9d9', '#969696'),
                      name="Degree of Militarization of Law Enforcement",
                      breaks=c("Militarized Police",
                               "Paramilitary Police", 
                               "Limited constabularization of the military",
                               "Generalized constabularization of the military")) + 
           guides(colour = guide_legend(nrow = 2))
  
  latam <- latam + theme_map()
  
  ggsave("Fig3.tiff", plot=latam, width=9,height=10, units = "in", dpi = 300)
  

